<template>
  <el-card class="valuation-card" shadow="hover">
    <div class="page-title">评估分诊</div>
    <el-tabs v-model="activeTab" class="tab-container" @tab-click="handleTabChange">
      <el-tab-pane label="待评估" name="tab1"></el-tab-pane>
      <el-tab-pane label="已评估" name="tab2"></el-tab-pane>
    </el-tabs>

    <div class="search-container">
      <el-select v-model="searchChannel" placeholder="请选择预约渠道" class="search-select" clearable @change="handleChannelChange">
        <el-option label="线下预约" value="线下预约"></el-option>
        <el-option label="线上预约" value="线上预约"></el-option>
      </el-select>
      <el-input
        v-model="searchKeyword"
        placeholder="请输入学生姓名/账号/学号/联系电话关键词查询"
        class="search-input"
        clearable
        @input="handleInput"
        @clear="resetSearch"
      />
      <el-button type="primary" @click="handleSearch" :disabled="!searchKeyword && !searchChannel">查询</el-button>
      <el-button @click="resetSearch" :disabled="!hasSearched" class="ml-2">返回</el-button>
    </div>

    <!-- 待评估表格 -->
    <el-table
      v-if="activeTab === 'tab1'"
      ref="tableRef"
      :data="paginatedPendingData"
      border
      style="width: 100%; margin-top: 20px"
      :row-class-name="tableRowClassName"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" width="70">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="学生姓名"></el-table-column>
      <el-table-column prop="studentId" label="账号/学号"></el-table-column>
      <el-table-column prop="healthScale" label="心理量表1"></el-table-column>
      <el-table-column prop="exerciseScale" label="心理量表2"></el-table-column>
      <el-table-column prop="department" label="学院"></el-table-column>
      <el-table-column prop="tutor" label="责任辅导员"></el-table-column>
      <el-table-column prop="phone" label="联系电话"></el-table-column>
      <el-table-column prop="channel" label="预约渠道" width="120"></el-table-column>
      <el-table-column prop="operation" label="操作" width="120">
        <template #default="scope">
          <el-button type="text" @click="handleValuate(scope.row)">
            {{ scope.row.valuationStatus === '已评估' ? '查看详情' : '录入结果' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 已评估表格 -->
    <el-table
      v-else
      :data="paginatedArrangedData"
      border
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column label="序号" width="70">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="学生姓名"></el-table-column>
      <el-table-column prop="studentId" label="账号/学号"></el-table-column>
      <el-table-column prop="healthScale" label="心理量表1"></el-table-column>
      <el-table-column prop="exerciseScale" label="心理量表2"></el-table-column>
      <el-table-column prop="department" label="学院"></el-table-column>
      <el-table-column prop="tutor" label="责任辅导员"></el-table-column>
      <el-table-column prop="phone" label="联系电话"></el-table-column>
      <el-table-column prop="channel" label="预约渠道"></el-table-column>
      <el-table-column prop="valuator" label="评估人员"></el-table-column>
      <el-table-column prop="valuateTime" label="评估时间"></el-table-column>
      <el-table-column prop="evaluationResult" label="评估结果"></el-table-column>
      <el-table-column prop="medicalDiagnosis" label="该生目前是否需要医学诊断或再次医学诊断"></el-table-column>
      <el-table-column prop="feedbackToAdmin" label="评估人是否需要向个案管理员反馈评估"></el-table-column>
      <el-table-column prop="consultationPriority" label="咨询优先级" width="120"></el-table-column>
    </el-table>

    <!-- 待评估分页和批量操作 -->
    <div class="pagination-container" v-if="activeTab === 'tab1'">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPendingPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pendingPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredPendingData.length"
        class="pagination"
      >
        <template #total>总共 {{ filteredPendingData.length }} 个</template>
      </el-pagination>

      <el-button
        type="primary"
        @click="handleBatchValuate"
        :disabled="!selectedRows.length"
        class="batch-button"
      >
        批量录入结果 ({{ selectedRows.length }})
      </el-button>
    </div>

    <!-- 已评估分页 -->
    <el-pagination
      v-else
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentArrangedPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="arrangedPageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredArrangedData.length"
      class="pagination"
    >
      <template #total>总共 {{ filteredArrangedData.length }} 个</template>
    </el-pagination>

    <!-- 评估表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="isBatch ? '批量健康评估' : '健康评估'" width="50%">
      <el-form :model="valuateForm" :rules="rules" ref="valuateFormRef" label-width="120px">
        <el-form-item label="评估结果" prop="evaluationResult">
          <el-radio-group v-model="valuateForm.evaluationResult">
            <el-radio label="极少心理问题">极少心理问题</el-radio>
            <el-radio label="轻度心理问题">轻度心理问题</el-radio>
            <el-radio label="中度心理问题">中度心理问题</el-radio>
            <el-radio label="严重心理问题">严重心理问题</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="处理建议1" prop="handleAdvice1">
          <el-checkbox-group v-model="valuateForm.handleAdvice1">
            <el-checkbox label="该生目前是否需要医学诊断或再次医学诊断：否" />
            <el-checkbox
              label="该生目前是否需要医学诊断或再次医学诊断：是（若是，该生是否同意）"
              @change="handleAgreeChange1"
            />
            <el-checkbox
              v-if="showAgreeCheckbox1"
              label="是（若是，该生是否同意）需继续勾选 是否同意"
            />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="处理建议2" prop="handleAdvice2">
          <el-checkbox-group v-model="valuateForm.handleAdvice2">
            <el-checkbox label="评估人是否需要向个案管理员反馈评估：否" />
            <el-checkbox
              label="评估人是否需要向个案管理员反馈评估：是（若是，请务必联系告知个案管理员）"
              @change="handleAgreeChange2"
            />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="咨询优先级" prop="consultationPriority">
          <el-radio-group v-model="valuateForm.consultationPriority" @change="handlePriorityChange">
            <el-radio label="目前不需要">目前不需要</el-radio>
            <el-radio label="优先安排">优先安排</el-radio>
            <el-radio label="正常排队">正常排队</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="valuateForm.consultationPriority !== '目前不需要'">
          <el-form-item label="可预约咨询师" prop="consultantId">
            <el-select
              v-model="valuateForm.consultantId"
              placeholder="请输入咨询师姓名或手机号关键词选择"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in consultantOptions"
                :key="item.id"
                :label="`${item.name}(${item.phone})`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="可咨询时间段" prop="availableTime">
            <el-date-picker
              v-model="valuateForm.availableTime"
              type="datetime"
              placeholder="选择日期和时间"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="咨询地点" prop="consultationLocation">
            <el-input
              v-model="valuateForm.consultationLocation"
              placeholder="请输入咨询地点，详细到门牌号"
            />
          </el-form-item>

          <el-alert
            v-if="valuateForm.consultationPriority === '优先安排'"
            title="优先排队需要学生在移动端上'我的咨询'中操作确认咨询师和时间的安排，确认接收后的学生直接进入'咨询过程管理'中开始咨询"
            type="info"
            :closable="false"
            show-icon
          />

          <el-alert
            v-if="valuateForm.consultationPriority === '正常排队'"
            title="正常排队需要学生在移动端上'我的咨询'中操作确认咨询师和时间的安排，确认接收后的学生直接进入'咨询过程管理'中开始咨询"
            type="info"
            :closable="false"
            show-icon
          />
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmValuate">提交</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, reactive, nextTick } from 'vue';
import valuateAPI from "../../api/mockData/valuate";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';

const activeTab = ref('tab1');
const searchKeyword = ref('');
const searchChannel = ref('');
const tableData = ref<any[]>([]);
const currentPendingPage = ref(1);
const pendingPageSize = ref(5);
const currentArrangedPage = ref(1);
const arrangedPageSize = ref(5);
const dialogVisible = ref(false);
const isBatch = ref(false);
const valuateFormRef = ref<FormInstance>();
const tableRef = ref(null);
const showAgreeCheckbox1 = ref(false);
const showAgreeCheckbox2 = ref(false);
const hasSearched = ref(false);

// 待评估和已评估的数据
const pendingData = ref<any[]>([]);
const arrangedData = ref<any[]>([]);

// 当前操作的行数据
const currentRow = ref<any>(null);
const selectedRows = ref<any[]>([]);

const consultantOptions = ref([
  { id: 1, name: '王瑶', phone: '17780104153' },
  { id: 2, name: '向珈君', phone: '13822223333' },
  { id: 3, name: '庄凯茜', phone: '13933334444' },
  { id: 4, name: '李欣宇', phone: '15888888888' }
]);

const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '明天',
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: '一周后',
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};

const valuateForm = reactive({
  evaluationResult: '',
  handleAdvice1: [],
  handleAdvice2: [],
  consultationPriority: '',
  consultantId: '',
  availableTime: null,
  consultationLocation: ''
});

const rules = reactive<FormRules>({
  evaluationResult: [{ required: true, message: '请选择评估结果', trigger: 'change' }],
  handleAdvice1: [{ required: true, message: '请选择处理建议1', trigger: 'change' }],
  handleAdvice2: [{ required: true, message: '请选择处理建议2', trigger: 'change' }],
  consultationPriority: [{ required: true, message: '请选择咨询优先级', trigger: 'change' }],
  consultantId: [{
    required: true,
    message: '请选择可预约咨询师',
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (valuateForm.consultationPriority !== '目前不需要' && !value) {
        callback(new Error('请选择可预约咨询师'));
      } else {
        callback();
      }
    }
  }],
  availableTime: [{
    required: true,
    message: '请选择可咨询时间段',
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (valuateForm.consultationPriority !== '目前不需要' && !value) {
        callback(new Error('请选择可咨询时间段'));
      } else {
        callback();
      }
    }
  }],
  consultationLocation: [{
    required: true,
    message: '请输入咨询地点',
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (valuateForm.consultationPriority !== '目前不需要' && !value) {
        callback(new Error('请输入咨询地点'));
      } else {
        callback();
      }
    }
  }]
});

// 获取数据
const fetchData = async () => {
  try {
    const res = await valuateAPI.getValuationData();
    if (res?.status) {
      tableData.value = res.data?.tableData || [];

      // 根据valuationStatus字段分离数据
      pendingData.value = (res.data?.tableData || []).filter((item: any) => item?.valuationStatus === '待评估');
      arrangedData.value = (res.data?.tableData || []).filter((item: any) => item?.valuationStatus === '已评估');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取评估数据失败');
  }
};

fetchData();

// 过滤待评估数据
const filteredPendingData = computed(() => {
  let data = [...pendingData.value];

  if (searchChannel.value) {
    data = data.filter(item => item.channel === searchChannel.value);
  }

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    data = data.filter(item =>
      item.name?.toLowerCase().includes(keyword) ||
      item.studentId?.toLowerCase().includes(keyword) ||
      item.phone?.toLowerCase().includes(keyword)
    );
  }

  return data;
});

// 过滤已评估数据
const filteredArrangedData = computed(() => {
  let data = [...arrangedData.value];

  if (searchChannel.value) {
    data = data.filter(item => item.channel === searchChannel.value);
  }

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    data = data.filter(item =>
      item.name?.toLowerCase().includes(keyword) ||
      item.studentId?.toLowerCase().includes(keyword) ||
      item.phone?.toLowerCase().includes(keyword)
    );
  }

  return data;
});

// 分页待评估数据
const paginatedPendingData = computed(() => {
  const start = (currentPendingPage.value - 1) * pendingPageSize.value;
  const end = start + pendingPageSize.value;
  return filteredPendingData.value.slice(start, end);
});

// 分页已评估数据
const paginatedArrangedData = computed(() => {
  const start = (currentArrangedPage.value - 1) * arrangedPageSize.value;
  const end = start + arrangedPageSize.value;
  return filteredArrangedData.value.slice(start, end);
});

const handleTabChange = () => {
  currentPendingPage.value = 1;
  currentArrangedPage.value = 1;
  resetSearch();
};

const handleSearch = () => {
  currentPendingPage.value = 1;
  currentArrangedPage.value = 1;
  hasSearched.value = true;
};

const handleChannelChange = () => {
  currentPendingPage.value = 1;
  currentArrangedPage.value = 1;
  hasSearched.value = !!searchChannel.value || !!searchKeyword.value;
};

const resetSearch = () => {
  searchKeyword.value = '';
  searchChannel.value = '';
  currentPendingPage.value = 1;
  currentArrangedPage.value = 1;
  hasSearched.value = false;
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};

const handleInput = () => {
  if (!searchKeyword.value.trim() && !searchChannel.value) {
    resetSearch();
  }
};

const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows || [];
};

const handleValuate = (row: any) => {
  if (!row) return;

  if (row.valuationStatus === '已评估') {
    // 已评估记录查看详情
    // 这里可以打开详情对话框
  } else {
    // 待评估记录录入结果
    isBatch.value = false;
    currentRow.value = row;
    dialogVisible.value = true;
    // 重置表单
    Object.assign(valuateForm, {
      evaluationResult: '',
      handleAdvice1: [],
      handleAdvice2: [],
      consultationPriority: '',
      consultantId: '',
      availableTime: null,
      consultationLocation: ''
    });
    showAgreeCheckbox1.value = false;
    showAgreeCheckbox2.value = false;
  }
};

const handleBatchValuate = () => {
  // 检查是否有待评估的选中项
  const pendingSelected = selectedRows.value.filter((item: any) => item?.valuationStatus === '待评估') || [];
  if (!pendingSelected.length) {
    ElMessage.warning('请选择待评估的记录');
    return;
  }

  ElMessageBox.confirm(`确定要批量评估选中的 ${pendingSelected.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isBatch.value = true;
    dialogVisible.value = true;
    // 重置表单
    Object.assign(valuateForm, {
      evaluationResult: '',
      handleAdvice1: [],
      handleAdvice2: [],
      consultationPriority: '',
      consultantId: '',
      availableTime: null,
      consultationLocation: ''
    });
    showAgreeCheckbox1.value = false;
    showAgreeCheckbox2.value = false;
  }).catch(() => {
    // 用户取消
  });
};

const handleSizeChange = (val: number) => {
  if (activeTab.value === 'tab1') {
    pendingPageSize.value = val;
    currentPendingPage.value = 1;
  } else {
    arrangedPageSize.value = val;
    currentArrangedPage.value = 1;
  }
};

const handleCurrentChange = (val: number) => {
  if (activeTab.value === 'tab1') {
    currentPendingPage.value = val;
  } else {
    currentArrangedPage.value = val;
  }
};

const handlePriorityChange = (val: string) => {
  if (val === '目前不需要') {
    valuateForm.consultantId = '';
    valuateForm.availableTime = null;
    valuateForm.consultationLocation = '';
  }
};

const moveToArranged = (rows: any[]) => {
  // 从待评估中移除选中的行
  const remainingPending = pendingData.value.filter(item =>
    !rows.some(row => row.id === item.id)
  );
  pendingData.value = remainingPending;

  // 获取咨询师信息
  const consultant = consultantOptions.value.find(c => c.id === valuateForm.consultantId);

  // 更新选中的行并添加到已评估
  const updatedRows = rows.map(row => {
    return {
      ...row,
      valuationStatus: '已评估',
      evaluationResult: valuateForm.evaluationResult,
      medicalDiagnosis: valuateForm.handleAdvice1.includes('该生目前是否需要医学诊断或再次医学诊断：否') ? '否' : '是',
      feedbackToAdmin: valuateForm.handleAdvice2.includes('评估人是否需要向个案管理员反馈评估：否') ? '否' : '是',
      consultationPriority: valuateForm.consultationPriority,
      valuator: consultant ? `${consultant.name}(${consultant.phone})` : '',
      valuateTime: valuateForm.availableTime ? formatDateTime(valuateForm.availableTime) : ''
    };
  });

  arrangedData.value = [...updatedRows, ...arrangedData.value];

  // 重置分页
  currentPendingPage.value = 1;
  currentArrangedPage.value = 1;
};

const confirmValuate = async () => {
  if (!valuateFormRef.value) return;
  try {
    // 表单验证
    await valuateFormRef.value.validate();

    if (isBatch.value) {
      // 批量评估逻辑
      const pendingSelected = selectedRows.value.filter((item: any) => item?.valuationStatus === '待评估') || [];
      if (!pendingSelected.length) {
        ElMessage.warning('请选择待评估的记录');
        return;
      }

      moveToArranged(pendingSelected);
      ElMessage.success(`成功批量评估 ${pendingSelected.length} 条记录`);

      nextTick(() => {
        if (tableRef.value) {
          tableRef.value.clearSelection();
        }
      });
    } else {
      // 单个评估逻辑
      if (currentRow.value) {
        moveToArranged([currentRow.value]);
        ElMessage.success('评估成功');
      } else {
        ElMessage.warning('请先选择一条记录');
      }
    }

    dialogVisible.value = false;
  } catch (error) {
    console.log('表单验证失败', error);
  }
};

// 格式化日期时间
const formatDateTime = (date: Date) => {
  if (!date) return '';
  try {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}/${month}/${day} ${hours}:${minutes}:00`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return '';
  }
};

// 行样式：双量表分数低于60分时高亮
const tableRowClassName = ({ row }: { row: any }) => {
  try {
    if (!row) return '';
    const healthScore = parseInt(row.healthScale?.replace('分', '') || '0');
    const exerciseScore = parseInt(row.exerciseScale?.replace('分', '') || '0');
    if (healthScore < 60 && exerciseScore < 60) {
      return 'highlight-row';
    }
    return '';
  } catch (error) {
    console.error('计算行样式出错:', error);
    return '';
  }
};

const handleAgreeChange1 = (val: boolean) => {
  showAgreeCheckbox1.value = val;
  if (!val) {
    valuateForm.handleAdvice1 = valuateForm.handleAdvice1?.filter(
      (item: string) => item !== '是（若是，该生是否同意）需继续勾选 是否同意'
    ) || [];
  } else {
    valuateForm.handleAdvice1 = [...(valuateForm.handleAdvice1 || []), '是（若是，该生是否同意）需继续勾选 是否同意'];
  }
};

const handleAgreeChange2 = (val: boolean) => {
  showAgreeCheckbox2.value = val;
};
</script>

<style scoped>
.valuation-card {
  margin: 20px;
  padding: 20px;
  position: relative;
  min-height: 80vh;
}
.page-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}
.assessment-stats {
  margin-bottom: 20px;
}
.assessment-stats span {
  margin-right: 20px;
  font-size: 14px;
  color: #666;
}
.tab-container {
  margin-bottom: 20px;
}
.search-container {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}
.search-input {
  width: 300px;
  margin-right: 10px;
}
.search-select {
  width: 150px;
  margin-right: 10px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination {
  margin-top: 0 !important;
  flex-grow: 1;
}

.batch-button {
  margin-left: 20px;
  white-space: nowrap;
}

::v-deep .highlight-row {
  background-color: #fef0f0;
}
::v-deep .highlight-row td {
  color: #f56c6c;
}
::v-deep .el-form-item__label {
  font-weight: bold;
}
::v-deep .el-radio {
  margin-right: 15px;
}
::v-deep .el-checkbox {
  display: block;
  margin-bottom: 8px;
}
</style>